<?php
/**
 * Created by PhpStorm.
 * User: drapeo
 * Date: 2015/5/21
 * Time: 21:06
 */

namespace Common\Model;
use Think\Model\MongoModel;

abstract class MongoDbModel extends MongoModel {
    public function __construct($name='',$tablePrefix='',$connection=''){
        $config = C('MONGODB_CONFIG');
        $this->dbName = $config['DB_NAME'];
        $this->tablePrefix = $config['DB_PREFIX'];
        parent::__construct($name,$config['DB_PREFIX'],$config);
    }

    protected function getInt($integer){
        return is_int($integer) ? $integer : intval($integer);
    }

    protected function getFloat($float){
        return is_float($float) ? $float : floatval($float);
    }

    protected function getString($str){
        return is_string($str) ? $str : strval($str);
    }

    // 表达式过滤回调方法
    protected function _options_filter(&$options) {
        $id = $this->getPk();
        if(isset($options['where'][$id]) && $this->_idType== self::TYPE_OBJECT){
            if(is_scalar($options['where'][$id])){
                //标量
                $options['where'][$id] = new \MongoId($options['where'][$id]);
            } else if(is_array($options['where'][$id])){
                if(is_scalar($options['where'][$id][1])){
                    $options['where'][$id][1] = explode(',',$options['where'][$id][1]);
                }
                //数组
                if(is_array($options['where'][$id][1])){
                    foreach($options['where'][$id][1] as &$_id){
                        $_id = new \MongoId($_id);
                    }
                }
            }
        }
    }

    /**
     * 获取自増的值
     * @param $name
     */
    protected function getIncrId($name){
        $update= array('$inc'=>array('id'=>1));
        $query= array('name'=>$name);

        $command= array(
            'findandmodify'=>'ids',
            'update'=>$update,
            'query'=>$query,
            'new'=>true,'upsert'=>true
        );
        $id= $this->command($command);

        return $id['value']['id'];
    }
}